import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

// types
const types = {
  SET_LOCATION: 'SET_LOCATION',
  SET_ADDRESS: 'SET_ADDRESS',
  ORDER_INFO:"ORDER_INFO",  
  //这里是为了在浏览器vue插件里，能够看到对应的名字
  //所以设置了type
  USER_INFO: 'USER_INFO',
  REMARK_INFO: 'REMARK_INFO'
};

// state
const state = {
  location: {},	//定位位置
  address: '',	//详细地址
  orderInfo: null,	 //订单信息，用来给结算页面提供选中的商品信息
  userInfo: null,  //用户信息，给订单结算提供用户收货地址等信息
  remarkInfo: {
    tableware: '',
    remark: ''
  }
};

// getters
const getters = {
  location: state => state.location,
  address: state => state.address,
  orderInfo:state=>state.orderInfo,
  userInfo: state => state.userInfo,
  totalPrice: state => {
    let price = 0;
    if (state.orderInfo) {
      const selectFoods = state.orderInfo.selectFoods;
      selectFoods.forEach(food => {
        price += food.activity.fixed_price * food.count;
      });
      price += state.orderInfo.shopInfo.float_delivery_fee;
    }
    return price;
  },
  remarkInfo: state => state.remarkInfo
};

// mutations
const mutations = {
  [types.SET_LOCATION](state, location) {
    if (location) {
      state.location = location;
    } else {
      state.location = null;
    }
  },
  [types.SET_ADDRESS](state, address) {
    if (address) {
      state.address = address;
    } else {
      state.address = '';
    }
  },
  //这里方括号是调用类型，后面是对应的函数方法
  [types.ORDER_INFO](state, orderInfo) {
    if (orderInfo) {
      state.orderInfo = orderInfo;
    } else {
      state.address = null;
    }
  },
  [types.USER_INFO](state, userInfo) {
    if (userInfo) {
      state.userInfo = userInfo;
    } else {
      state.userInfo = null;
    }
  },
  [types.REMARK_INFO](state, remarkInfo) {
    if (remarkInfo) {
      state.remarkInfo = remarkInfo;
    } else {
      state.remarkInfo = null;
    }
  }
};

// actions
//这里的action是外面调用vuex的接口方法,用dispatch方法调用
const actions = {
  setLocation: ({ commit }, location) => {
    commit(types.SET_LOCATION, location);
  },
  setAddress: ({ commit }, address) => {
    commit(types.SET_ADDRESS, address);
  },
  setOrderInfo: ({ commit }, orderInfo) => {
    commit(types.ORDER_INFO, orderInfo);
  },
  setUserInfo: ({ commit }, userInfo) => {
    commit(types.USER_INFO, userInfo);
  },
  setRemarkInfo: ({ commit }, remarkInfo) => {
    commit(types.REMARK_INFO, remarkInfo);
  }
};



export default new Vuex.Store({
  state,
  getters,
  mutations,
  actions
})
